package com.ledi.guns.modular.ledipay.service.impl;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.ledi.guns.common.exception.AppCheckException;
import com.ledi.guns.common.persistence.dao.BillDetailMapper;
import com.ledi.guns.common.persistence.dao.OrderPayStreamMapper;
import com.ledi.guns.common.persistence.dao.PayRecordAlipayMapper;
import com.ledi.guns.common.persistence.dao.PayRecordWeixinMapper;
import com.ledi.guns.common.persistence.dao.SchoolInfoMapper;
import com.ledi.guns.common.persistence.dao.SmsSendMapper;
import com.ledi.guns.common.persistence.dao.UserMapper;
import com.ledi.guns.common.persistence.model.OrderPayStream;
import com.ledi.guns.common.persistence.model.PayRecordAlipay;
import com.ledi.guns.common.persistence.model.PayRecordWeixin;
import com.ledi.guns.common.persistence.model.SchoolInfo;
import com.ledi.guns.common.persistence.model.SmsSend;
import com.ledi.guns.common.persistence.model.User;
import com.ledi.guns.common.persistence.model.vo.BillDetailVo;
import com.ledi.guns.common.persistence.model.vo.SmsBalanceVo;
import com.ledi.guns.common.persistence.model.vo.SmsSchoolUseVo;
import com.ledi.guns.common.persistence.page.PageQuery;
import com.ledi.guns.core.base.tips.SuccessTip;
import com.ledi.guns.core.shiro.ShiroKit;
import com.ledi.guns.core.shiro.ShiroUser;
import com.ledi.guns.core.util.DateUtil;
import com.ledi.guns.core.util.IdGenerator;
import com.ledi.guns.core.util.PayUtil;
import com.ledi.guns.core.util.SystemConstans;
import com.ledi.guns.modular.ledipay.controller.feignClients.SmsApi;
import com.ledi.guns.modular.ledipay.controller.feignClients.req.SchoolSmsUseReq;
import com.ledi.guns.modular.ledipay.controller.feignClients.req.SmsBuyRecord;
import com.ledi.guns.modular.ledipay.controller.feignClients.req.SmsPackageReq;
import com.ledi.guns.modular.ledipay.controller.feignClients.req.SmsSchoolBuyRecord;
import com.ledi.guns.modular.ledipay.controller.feignClients.req.SmsSchoolGiveReq;
import com.ledi.guns.modular.ledipay.controller.feignClients.req.SmsSchoolRecord;
import com.ledi.guns.modular.ledipay.controller.feignClients.req.SmsSchoolReq;
import com.ledi.guns.modular.ledipay.controller.feignClients.response.SmsPackage;
import com.ledi.guns.modular.ledipay.controller.req.SmsMessageReq;
import com.ledi.guns.modular.ledipay.controller.req.sms.GetCode;
import com.ledi.guns.modular.ledipay.controller.req.sms.MobileAndBill;
import com.ledi.guns.modular.ledipay.controller.req.sms.PromptPaymentReq;
import com.ledi.guns.modular.ledipay.controller.req.sms.SmsSendRecordReq;
import com.ledi.guns.modular.ledipay.service.SmsService;

/**
 * 文件名称： com.ledi.guns.modular.ledipay.service.impl.SmsServiceImpl.java<br/>
 * 初始作者： 钟小平<br/>
 * 创建日期： 2018年7月9日<br/>
 * 功能说明： 短信套餐service实现 <br/>
 * =================================================<br/>
 * 修改记录：<br/>
 * 修改作者 日期 修改内容<br/>
 * ================================================<br/>
 * Copyright (乐迪教育科技有限公司-幼儿事业部) 2017-2018.All rights reserved.<br/>
 */
@Service
public class SmsServiceImpl implements SmsService {

	protected final static Logger logger = LoggerFactory.getLogger(SmsServiceImpl.class);
	@Autowired
	private UserMapper userMapper;

	@Autowired
	private SmsApi smsApi;
	@Autowired
	private SchoolInfoMapper schoolInfoMapper;
	@Autowired
	private OrderPayStreamMapper orderPayStreamMapper;
	@Autowired
	private PayRecordAlipayMapper payRecordAlipayMapper;
	@Autowired
	private PayRecordWeixinMapper payRecordWeixinMapper;
	@Autowired
	private SmsSendMapper smsSendMapper;
	@Autowired
	private BillDetailMapper billDetailMapper;

	@Value("${weixin.appid}")
	private String weixinAppid;
	@Value("${ali.appid}")
	private String alipayAppid;
	@Value("${ali.priKey}")
	private String alipayPriKey;
	@Value("${ali.alipayNotify}")
	private String alipayNotify;
	@Value("${weixin.secret}")
	private String secret;
	@Value("${weixin.openIdUrl}")
	private String openIdUrl;
	@Value("${weixin.mchId}")
	private String mchId;
	@Value("${weixin.shhkey}")
	private String shhkey;
	@Value("${weixin.weixinPayUrl}")
	private String weixinPayUrl;
	@Value("${weixin.smsWeixinNotify}")
	private String weixinNotify;

	/**
	 * 方法描述: [套餐列表.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月10日-下午3:27:03<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public Map list(Integer status) {

		return smsApi.smsPackageList(status);
	}

	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map add(SmsPackageReq param) {

		ShiroUser currentUser = ShiroKit.getUser();
		if (param.getId() == null) {
			param.setCreateTime(new Date());
			param.setCreatorId(Long.parseLong(currentUser.getId() + ""));
		} else {
			Map<String, Object> map = smsApi.getSmsPackageById(param.getId());
			if (map.get("code").equals(200)) {
				String data = JSON.toJSONString(map.get("data"));
				SmsPackage s = JSON.parseObject(data, SmsPackage.class);
				if (s == null || s.getIsDelete() == SystemConstans.YES) {

					throw new AppCheckException("school.sms.package.null.code", "school.sms.package.null.message");
				}
				if (s.getVersionNo() != param.getVersionNo()) {
					throw new AppCheckException("versionNo.outofDate.code", "versionNo.outofDate.message");
				}
				param.setStatus(s.getStatus());
			}
			param.setCreateTime(new Date());
			param.setCreatorId(Long.parseLong(currentUser.getId() + ""));
			param.setUpdateTime(new Date());
			param.setUpdaterId(Long.parseLong(currentUser.getId() + ""));
		}
		BigDecimal presentPrice = param.getPresentPrice();
		BigDecimal originPrice = param.getOriginPrice();
		if (presentPrice != null && originPrice != null) {
			if (presentPrice.compareTo(param.getOriginPrice()) > 0) {
				throw new AppCheckException("school.sms.presentPrice.inactive.code", "school.sms.presentPrice.inactive.message");
			}
		}
		return smsApi.addSmsPackage(param);
	}

	/**
	 * 方法描述: [删除套餐.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月11日-上午10:04:32<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map delete(SmsPackageReq param) {

		param.setIsDelete(SystemConstans.YES);
		return smsApi.delete(param);
	}

	/**
	 * 方法描述: [分配学校赠送短信.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月11日-下午3:05:44<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addSchoolSmsGive(SmsSchoolGiveReq param) {

		ShiroUser currentUser = ShiroKit.getUser();
		if (param.getId() == null) {
			param.setCreateTime(new Date());
			param.setCreatorId(Long.parseLong(currentUser.getId() + ""));
		} else {
			param.setUpdateTime(new Date());
			param.setUpdaterId(Long.parseLong(currentUser.getId() + ""));
		}
		SchoolInfo selectById = schoolInfoMapper.selectById(param.getSchoolId());
		if (selectById != null) {
			selectById.setId(param.getSchoolId());
			selectById.setFreeMonth(param.getFreeMonth());
			selectById.setGiveCount(param.getGiveCount());
			selectById.setUpdateTime(new Date());
			selectById.setUpdaterId(Long.parseLong(currentUser.getId() + ""));
			schoolInfoMapper.updateById(selectById);
			// smsApi.addSmsSchoolGive(param);
			// 后台购买数量减去相应是的数目 param.getGiveSmsCount()
			Map<String, Object> mapSms = smsApi.getTopSmsBuyBalance();
			if (mapSms.get("code").equals(200)) {
				String buy = JSON.toJSONString(mapSms.get("data"));
				if (!buy.equals("null")) {
					SmsBuyRecord smsBuyRecord = JSON.parseObject(buy, SmsBuyRecord.class);
					if (smsBuyRecord.getBalanceCount() < param.getGiveCount()) {
						throw new AppCheckException("sms.school.balance.notEnough.exit.code", "sms.school.balance.notEnough.exit.message");
					}
					smsBuyRecord.setSmsBuyCount(-param.getGiveCount());
					smsBuyRecord.setUpdateTime(new Date());
					smsBuyRecord.setUpdaterId(Long.parseLong(currentUser.getId() + ""));
					smsBuyRecord.setCreatorName(currentUser.getName());
					smsApi.smsBuyAdd(smsBuyRecord);
				}
			}

			// 自动分配学校
			// giveSchoolsms();

		} else {
			throw new AppCheckException("school.noSchool.code", "school.noSchool.message");
		}
	}

	@Override
	public Map officialPrice() {

		return smsApi.officialPrice();
	}

	@Override
	public Map<String, Object> smsSchoolList(SmsSchoolReq smsSchoolReq) {

		if (smsSchoolReq.getStartTime() != null) {
			smsSchoolReq.setStartTime(DateUtil.formate(smsSchoolReq.getStartTime(), true));
		}
		if (smsSchoolReq.getEndTime() != null) {
			smsSchoolReq.setEndTime(DateUtil.formate(smsSchoolReq.getEndTime(), false));
		}
		Map<String, Object> schoolRecord = smsApi.schoolRecordList(smsSchoolReq);
		return schoolRecord;
	}

	/**
	 * 方法描述: [后台短信充值.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月13日-上午11:01:21<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public void addSmsBuy(Long smsBuyCount) {

		ShiroUser currentUser = ShiroKit.getUser();
		SmsBuyRecord param = new SmsBuyRecord();
		param.setCreateTime(new Date());
		param.setCreatorId(Long.parseLong(currentUser.getId() + ""));
		param.setCreatorName(currentUser.getName());
		param.setSmsBuyCount(smsBuyCount);
		smsApi.smsBuyAdd(param);
	}

	/**
	 * 方法描述: [后台短信充值列表.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月13日-上午11:01:33<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public Map smsBuyList(PageQuery query) {

		return smsApi.smsBuyList(query);
	}

	/**
	 * 方法描述: [后台短信余额.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月13日-下午12:35:32<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public String getSmsBuyBalance() {

		Map<String, Object> map = smsApi.getTopSmsBuyBalance();
		if (map.get("code").equals(200)) {
			String data = JSON.toJSONString(map.get("data"));
			if (data.equals("null")) {
				return "0";
			}
			SmsBuyRecord s = JSON.parseObject(data, SmsBuyRecord.class);
			return String.valueOf(s.getBalanceCount());
		}
		return "0";
	}

	/**
	 * 方法描述: [短信预充值.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月13日-下午2:35:58<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Map addSchoolRecord(SmsSchoolRecord param) {

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}

		Map<String, Object> map = smsApi.getSmsPackageById(param.getPackageId());
		if (map.get("code").equals(200)) {
			String data = JSON.toJSONString(map.get("data"));
			SmsPackage s = JSON.parseObject(data, SmsPackage.class);
			if (s == null || s.getIsDelete() == SystemConstans.YES) {
				throw new AppCheckException("school.sms.package.null.code", "school.sms.package.null.message");
			}
			if (s.getVersionNo() != param.getVersionNo()) {
				throw new AppCheckException("versionNo.outofDate.code", "versionNo.outofDate.message");
			}
			if (s.getStatus().equals(SystemConstans.NO)) {
				throw new AppCheckException("school.sms.package.inactive.code", "school.sms.package.inactive.message");
			}

			// 后台短信总量不能为0
			Map<String, Object> topSmsBuyBalance = smsApi.getTopSmsBuyBalance();
			if (topSmsBuyBalance.get("code").equals(200)) {
				String buy = JSON.toJSONString(topSmsBuyBalance.get("data"));
				if (!buy.equals("null")) {
					SmsBuyRecord smsBuyRecord = JSON.parseObject(buy, SmsBuyRecord.class);
					if (smsBuyRecord.getBalanceCount() <= 0) {
						throw new AppCheckException("sms.school.balance.notEnough.exit.code", "sms.school.balance.notEnough.exit.message");
					}
					if (s.getSmsCount() + s.getGiveSmsCount() > smsBuyRecord.getBalanceCount()) {
						throw new AppCheckException("sms.school.balance.notEnough.exit.code", "sms.school.balance.notEnough.exit.message");
					}
				} else {
					throw new AppCheckException("sms.school.balance.notEnough.exit.code", "sms.school.balance.notEnough.exit.message");
				}
			} else {
				throw new AppCheckException("sms.school.balance.notEnough.exit.code", "sms.school.balance.notEnough.exit.message");
			}

			if (param.getId() == null) {
				param.setCreateTime(new Date());
				param.setCreatorId(Long.parseLong(currentUser.getId() + ""));
				param.setStatus(SystemConstans.NO);
			} else {
				param.setUpdaterId(Long.parseLong(currentUser.getId() + ""));
				param.setUpdateTime(new Date());
				param.setStatus(SystemConstans.YES);
				// param.setDealNo(IdGenerator.getIdLong());
			}
			Long schoolId = oneUser.getSchoolId();
			if (schoolId == null) {
				throw new AppCheckException("school.user.noSchool.code", "school.user.noSchool.message");
			}
			SchoolInfo selectById = schoolInfoMapper.selectById(schoolId);
			if (selectById == null) {
				throw new AppCheckException("school.user.noSchool.code", "school.user.noSchool.message");
			}
			param.setSchoolId(schoolId);
			param.setSchoolName(selectById.getSchoolName());
			param.setName(s.getName());
			param.setGiveSmsCount(s.getGiveSmsCount());
			param.setSmsCount(s.getSmsCount());
			param.setPresentPrice(s.getPresentPrice());
			param.setOriginPrice(s.getOriginPrice());
			param.setOrderNo(IdGenerator.getIdLong());
		} else {
			throw new AppCheckException("school.sms.schoolRecord.false.code", "school.sms.schoolRecord.false.message");
		}
		return smsApi.addSchoolRecord(param);
	}

	/**
	 * 方法描述: [预支付.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月16日-上午11:03:41<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public Map<String, String> prePay(GetCode getCode, HttpServletRequest request) {

		ShiroUser currentUser = ShiroKit.getUser();
		SortedMap<String, String> orderSign = new TreeMap<String, String>();
		orderSign.put("orderNo", getCode.getOrderNo() + "");
		orderSign.put("key", SystemConstans.ORDER_PAY_WAY_WEIXIN);
		String orderSigns = PayUtil.createSign(orderSign);
		if (!orderSigns.equalsIgnoreCase(getCode.getOrderSign())) {
			throw new AppCheckException("order.pay.code", "order.pay.message", "签名错误");
		}
		Map<String, Object> map = smsApi.getSchoolRecord(getCode.getOrderNo());

		if (map.get("code").equals(200)) {
			String data = JSON.toJSONString(map.get("data"));
			SmsSchoolRecord sr = JSON.parseObject(data, SmsSchoolRecord.class);
			SortedMap<String, String> finalpackage = new TreeMap<String, String>();
			if (sr == null) {
				throw new AppCheckException("order.pay.code", "order.pay.message", "订单编号错误");
			}
			try {
				/*------1.根据code获取微信用户的openId和access_token------- */
				String openid = null;
				try {
					List<Object> list = accessToken(getCode.getCode());
					openid = list.get(1).toString();
				} catch (Exception e) {
					throw new AppCheckException("order.pay.code", "order.pay.message", "获取openId失败");
				}

				/*------2.生成预支付订单需要的的package数据------- */
				// 随机数
				String nonce_str = PayUtil.getNonceStr();
				// 订单生成的机器 IP
				String spbill_create_ip = request.getHeader("X-Real-IP");
				// 交易类型 ：jsapi代表微信公众号支付
				String trade_type = "JSAPI";
				// 这里notify_url是 微信处理完支付后的回调的应用系统接口url。
				String notify_url = weixinNotify;

				SortedMap<String, String> packageParams = new TreeMap<String, String>();
				packageParams.put("appid", weixinAppid);
				packageParams.put("mch_id", mchId);
				packageParams.put("nonce_str", nonce_str);
				packageParams.put("body", "短信费用");
				packageParams.put("out_trade_no", getCode.getOrderNo() + "");
				packageParams.put("total_fee", sr.getPresentPrice().multiply(new BigDecimal(100)).intValue() + "");
				packageParams.put("spbill_create_ip", spbill_create_ip);
				packageParams.put("notify_url", notify_url);
				packageParams.put("trade_type", trade_type);
				packageParams.put("openid", openid);

				/*------3.根据package数据生成预支付订单号的签名sign------- */
				packageParams.put("key", shhkey);
				String paySign = PayUtil.createSign(packageParams);
				packageParams.remove("key");
				packageParams.put("sign", paySign);

				/*------4.生成需要提交给统一支付接口的xml数据-------*/
				String xml = "";
				try {
					xml = PayUtil.mapToXml(packageParams);
					logger.error("【测试，查看提交给统一支付接口的xml数据】" + xml);
				} catch (Exception e) {
					logger.error("生成需要提交给统一支付接口的xml数据转换失败", e);
					throw new AppCheckException("order.pay.code", "order.pay.message", "xml数据转换失败");
				}

				/*------5.调用统一支付接口https://api.mch.weixin.qq.com/pay/unifiedorder 生产预支付订单----------*/

				Map payMap = PayUtil.getPayNo(weixinPayUrl, xml);
				logger.error("【测试，调用统一支付接口返回的数据】" + payMap.toString());
				// 签名失败 参数格式校验错误
				if ("FAIL".equals(payMap.get("return_code"))) {
					logger.error("[请求微信预支付接口失败：]" + (String) payMap.get("return_msg"));
					throw new AppCheckException("order.pay.code", "order.pay.message", (String) payMap.get("return_msg"));
				}
				// 请求后值是否错误
				if ("FAIL".equals(payMap.get("result_code"))) {
					logger.error("[请求微信预支付接口失败：]" + payMap.get("err_code_des"));
					throw new AppCheckException("order.pay.code", "order.pay.message", (String) payMap.get("err_code_des"));
				}

				/*------6.成功后进行入库操作----------*/
				SmsSchoolRecord schooRecord = new SmsSchoolRecord();
				schooRecord.setPayWay(SystemConstans.NO);
				schooRecord.setId(sr.getId());
				schooRecord.setDealNo(IdGenerator.getIdLong());
				schooRecord.setUpdateTime(new Date());
				schooRecord.setUpdaterId(Long.parseLong(currentUser.getId() + ""));
				smsApi.addSchoolRecord(schooRecord);
				// 时间戳
				String timestamp = String.valueOf(System.currentTimeMillis() / 1000);

				finalpackage.put("appId", weixinAppid);
				finalpackage.put("timeStamp", timestamp);
				finalpackage.put("nonceStr", PayUtil.getNonceStr());
				finalpackage.put("package", "prepay_id=" + payMap.get("prepay_id"));
				finalpackage.put("signType", "MD5");
				finalpackage.put("key", shhkey);
				finalpackage.put("sign", PayUtil.createSign(finalpackage));
				finalpackage.remove("key");

			} catch (Exception e) {
				if (e instanceof AppCheckException) {
					throw (AppCheckException) e;
				}
				throw new AppCheckException("order.pay.code", "order.pay.message", "统一支付接口获取预支付订单出错");
			}
			return finalpackage;
		}

		return null;
	}

	/**
	 * 通过微信用户的code换取网页授权access_token
	 *
	 * @throws IOException
	 * @throws ClientProtocolException
	 */
	private List<Object> accessToken(String code) throws ClientProtocolException, IOException {

		List<Object> list = new ArrayList<Object>();
		String url = openIdUrl + "?appid="
				+ weixinAppid + "&secret=" + secret + "&code=" + code + "&grant_type=authorization_code";
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(url);
		HttpResponse res = client.execute(post);
		if (res.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
			HttpEntity entity = res.getEntity();
			String str = org.apache.http.util.EntityUtils.toString(entity, "utf-8");
			ObjectMapper mapper = new ObjectMapper();
			Map<String, Object> jsonOb = mapper.readValue(str, Map.class);
			list.add(jsonOb.get("access_token"));
			list.add(jsonOb.get("openid"));
		}
		return list;
	}

	/**
	 * 方法描述: [扫描二维码.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月17日-下午1:25:39<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public String scan(String userMobile, String orderNo, String sign) {

		String msg = null;
		Map<String, Object> map = smsApi.getSchoolRecord(orderNo);
		if (map.get("code").equals(200)) {
			String data = JSON.toJSONString(map.get("data"));
			SmsSchoolRecord sr = JSON.parseObject(data, SmsSchoolRecord.class);
			SortedMap<String, String> finalpackage = new TreeMap<String, String>();
			if (sr == null) {
				throw new AppCheckException("order.pay.code", "order.pay.message", "订单编号错误");
			}

			SortedMap<String, String> commentSign = new TreeMap<String, String>();
			commentSign.put("orderNo", orderNo);
			commentSign.put("key", sr.getId() + "");
			commentSign.put("userMobile", userMobile);
			String csign = PayUtil.createSign(commentSign);
			if (!csign.equalsIgnoreCase(sign)) {
				msg = "签名错误";
			}
			if (sr.getStatus() != SystemConstans.NO) {
				msg = "订单状态不正确，不可以支付";
			}
			logger.error("----------------------" + msg);
			return msg;
		}
		return null;
	}

	/**
	 * 方法描述: [支付宝预支付.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月17日-下午1:25:54<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public String prePayOrder(String orderNo) {

		Map<String, Object> map = smsApi.getSchoolRecord(orderNo);
		if (map.get("code").equals(200)) {
			String data = JSON.toJSONString(map.get("data"));
			SmsSchoolRecord sr = JSON.parseObject(data, SmsSchoolRecord.class);
			SortedMap<String, String> finalpackage = new TreeMap<String, String>();
			if (sr == null) {
				throw new AppCheckException("order.pay.code", "order.pay.message", "订单编号错误");
			}
			// 公共请求参数
			Map<String, String> param = new HashMap<>();
			param.put("app_id", alipayAppid); // 应用appId
			param.put("method", "alipay.trade.wap.pay"); // 接口名称
			param.put("format", "json"); // 数据类型
			param.put("charset", "utf-8");// 编码格式
			param.put("timestamp", DateUtil.getTime());// 发送请求时间
			param.put("version", "1.0");// 调用接口版本，固定为1.0
			param.put("notify_url", alipayNotify);// 支付宝服务器主动通知商户服务
			logger.info("订单号:{},回调地址:{}", orderNo, alipayNotify);
			param.put("sign_type", "RSA2");// 签名类型
			// 支付业务请求参数
			Map<String, Object> pcont = new HashMap<>();
			pcont.put("out_trade_no", orderNo);// 订单号(综合采购单编号)
			pcont.put("total_amount", String.valueOf(sr.getPresentPrice()));// 交易金额
			pcont.put("subject", "费用"); // 订单标题
			pcont.put("body", "暂时不写描述"); // 对交易或商品的描述
			pcont.put("product_code", "QUICK_WAP_WAY"); // 销售产品码
			param.put("biz_content", JSON.toJSONString(pcont)); // 业务请求参数 不需要对json字符串转义
			String orderStr = null;
			try {
				param.put("sign", PayUtil.getSign(param, alipayPriKey)); // 业务请求参数
				orderStr = PayUtil.getSignEncodeUrl(param, true);
				OrderPayStream orderPayStream = new OrderPayStream();
				orderPayStream.setOrderId(sr.getId());
				orderPayStream.setPayWay(SystemConstans.ORDER_PAY_WAY_ALIPAY);
				orderPayStream.setApiUrl("https://openapi.alipay.com/gateway.do");
				orderPayStream.setApiName("支付宝统一下单接口");
				orderPayStream.setReqData(param.toString());
				orderPayStream.setReqTime(new Date());
				orderPayStream.setInvokeType("S");
				orderPayStream.setCreateTime(new Date());
				orderPayStreamMapper.insert(orderPayStream);

			} catch (Exception e) {
				e.printStackTrace();
			}
			return orderStr;
		}
		return null;
	}

	/**
	 * 方法描述: [提交支付后的支付宝异步返回接口.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月17日-下午3:57:52<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional
	public void alipayNotify(Map<String, String> params) {

		String reqData = getBodyString(params);
		logger.info("receive ali pay notify:" + reqData);
		String orderNo = params.get("out_trade_no");// 订单号
		String trade_no = params.get("trade_no");// 支付宝订单号
		String gmt_payment = params.get("gmt_payment");// 交易付款时间
		String total_amount = params.get("total_amount");// 订单金额
		Map<String, Object> map = smsApi.getSchoolRecord(orderNo);
		if (map.get("code").equals(200)) {
			String data = JSON.toJSONString(map.get("data"));
			SmsSchoolRecord sr = JSON.parseObject(data, SmsSchoolRecord.class);
			if (sr == null) {
				throw new AppCheckException("order.pay.code", "order.pay.message", "订单编号错误");
			}
			// 创建支付宝支付记录
			PayRecordAlipay payRecordAlipay = new PayRecordAlipay();
			payRecordAlipay.setPayTime(DateUtil.parseTime(gmt_payment));
			payRecordAlipay.setCreateTime(new Date());
			payRecordAlipay.setIsDelete(0);
			payRecordAlipay.setAlipayTransactionId(trade_no);
			payRecordAlipay.setOrderId(sr.getId());
			payRecordAlipayMapper.insert(payRecordAlipay);
			// 更新订单表数据
			sr.setStatus(SystemConstans.YES);
			sr.setPayWay(SystemConstans.NO);
			sr.setPayTime(DateUtil.parseTime(gmt_payment));
			sr.setDealNo(IdGenerator.getIdLong());
			smsApi.addSchoolRecord(sr);
			// 新增学校购买短信情况
			SmsSchoolBuyRecord param = new SmsSchoolBuyRecord();
			param.setSchoolId(sr.getSchoolId());
			param.setSmsBuyCount(sr.getSmsCount() + sr.getGiveSmsCount());
			param.setCreatorId(sr.getCreatorId());
			param.setCreateTime(new Date());
			param.setSchoolName(sr.getSchoolName());
			param.setVersionNo(SystemConstans.NO);
			param.setUpdateTime(new Date());
			param.setUpdaterId(sr.getCreatorId());
			smsApi.smsSchoolBuyAdd(param);
			// 后台购买数量减去相应是的数目sr.getSmsCount() + sr.getGiveSmsCount()
			Map<String, Object> mapSms = smsApi.getTopSmsBuyBalance();
			if (mapSms.get("code").equals(200)) {
				String buy = JSON.toJSONString(mapSms.get("data"));
				if (!buy.equals("null")) {
					SmsBuyRecord smsBuyRecord = JSON.parseObject(buy, SmsBuyRecord.class);
					smsBuyRecord.setSmsBuyCount(-(sr.getSmsCount() + sr.getGiveSmsCount()));
					smsBuyRecord.setUpdateTime(new Date());
					smsBuyRecord.setUpdaterId(sr.getCreatorId());
					smsApi.smsBuyAdd(smsBuyRecord);
				}
			}
			// 对外操作记录
			OrderPayStream orderPayStream = new OrderPayStream();
			orderPayStream.setOrderId(sr.getId());
			orderPayStream.setPayWay(SystemConstans.ORDER_PAY_WAY_ALIPAY);
			orderPayStream.setApiName("支付宝异步通知");
			orderPayStream.setReqData(reqData);
			orderPayStream.setReqTime(new Date());
			orderPayStream.setResData("success");
			orderPayStream.setResTime(new Date());
			orderPayStream.setInvokeType("R");
			orderPayStream.setCreateTime(new Date());
			orderPayStreamMapper.insert(orderPayStream);
		}
	}

	private String getBodyString(Map<String, String> params) {

		Set<String> keySet = params.keySet();
		StringBuilder str = new StringBuilder();
		try {
			for (String key : keySet) {
				if (str.length() > 0) {
					str.append("&");
				}
				str.append(key).append("=").append(params.get(key));
			}
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
		}
		return str.toString();
	}

	/**
	 * 方法描述: [提交支付后的微信异步返回接口.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月17日-下午3:57:55<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional
	public void weixinNotify(String resultStr) {

		Map<String, Object> resultMap = PayUtil.parseXmlToList(resultStr);
		String orderNo = null;
		String return_code = (String) resultMap.get("return_code");
		if (return_code.equals("SUCCESS")) {
			String result_code = (String) resultMap.get("result_code");
			if (result_code.equals("SUCCESS")) {
				String transaction_id = (String) resultMap.get("transaction_id");
				String openid = (String) resultMap.get("openid");// 用户标识
				String time_end = (String) resultMap.get("time_end");// 支付完成时间
				String total_fee = (String) resultMap.get("total_fee");// 订单金额
				String bank_type = (String) resultMap.get("bank_type");// 付款银行
				orderNo = (String) resultMap.get("out_trade_no");// 订单编号
				Map<String, Object> map = smsApi.getSchoolRecord(orderNo);
				if (map.get("code").equals(200)) {
					String data = JSON.toJSONString(map.get("data"));
					SmsSchoolRecord sr = JSON.parseObject(data, SmsSchoolRecord.class);
					if (sr == null) {
						throw new AppCheckException("order.pay.code", "order.pay.message", "订单编号错误");
					}
					// 创建微信支付记录
					PayRecordWeixin payRecordWeixin = new PayRecordWeixin();
					payRecordWeixin.setPayTime(DateUtil.parseDate1(time_end));
					payRecordWeixin.setCreateTime(new Date());
					payRecordWeixin.setIsDelete(0);
					payRecordWeixin.setOpenid(openid);
					payRecordWeixin.setOrderId(sr.getId());
					payRecordWeixin.setWeixinTransactionId(transaction_id);
					payRecordWeixinMapper.insert(payRecordWeixin);
					// 更新订单表数据
					sr.setStatus(SystemConstans.YES);
					sr.setPayWay(SystemConstans.NO);
					sr.setPayTime(DateUtil.parseTime(time_end));
					sr.setDealNo(IdGenerator.getIdLong());
					smsApi.addSchoolRecord(sr);
					// 新增学校购买短信情况
					SmsSchoolBuyRecord param = new SmsSchoolBuyRecord();
					param.setSchoolId(sr.getSchoolId());
					param.setSmsBuyCount(sr.getSmsCount() + sr.getGiveSmsCount());
					param.setCreatorId(sr.getCreatorId());
					param.setCreateTime(new Date());
					param.setSchoolName(sr.getSchoolName());
					param.setVersionNo(SystemConstans.NO);
					param.setUpdateTime(new Date());
					param.setUpdaterId(sr.getCreatorId());
					smsApi.smsSchoolBuyAdd(param);
					// 后台购买数量减去相应是的数目sr.getSmsCount() + sr.getGiveSmsCount()
					Map<String, Object> mapSms = smsApi.getTopSmsBuyBalance();
					if (mapSms.get("code").equals(200)) {
						String buy = JSON.toJSONString(mapSms.get("data"));
						if (!buy.equals("null")) {
							SmsBuyRecord smsBuyRecord = JSON.parseObject(buy, SmsBuyRecord.class);
							smsBuyRecord.setSmsBuyCount(-(sr.getSmsCount() + sr.getGiveSmsCount()));
							smsBuyRecord.setUpdateTime(new Date());
							smsBuyRecord.setUpdaterId(sr.getCreatorId());
							smsApi.smsBuyAdd(smsBuyRecord);
						}
					}
					// 对外操作记录
					OrderPayStream orderPayStream = new OrderPayStream();
					orderPayStream.setOrderId(sr.getId());
					orderPayStream.setPayWay(SystemConstans.ORDER_PAY_WAY_WEIXIN);
					orderPayStream.setApiName("微信异步通知");
					orderPayStream.setReqData(resultStr);
					orderPayStream.setReqTime(new Date());
					orderPayStream.setResData("success");
					orderPayStream.setResTime(new Date());
					orderPayStream.setInvokeType("R");
					orderPayStream.setCreateTime(new Date());
					orderPayStreamMapper.insert(orderPayStream);
				}
			}
		}

	}

	/**
	 * 方法描述: [短信催缴费.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月18日-上午9:56:16<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public int promptPayment(PromptPaymentReq req) {

		List<MobileAndBill> splitMobile = req.getMobileAndBill();
		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		if (oneUser.getSchoolId() == null) {
			throw new AppCheckException("school.noSchool.code", "school.noSchool.message");
		}
		SchoolInfo selectById = schoolInfoMapper.selectById(oneUser.getSchoolId());
		if (selectById != null) {

			List<SmsSend> smsList = new ArrayList<SmsSend>();
			// 发送成功的短信
			List<Integer> successSms = new ArrayList<Integer>();
			for (MobileAndBill mobileAndBill : splitMobile) {
				BillDetailVo detail = billDetailMapper.getBillDetaileById(mobileAndBill.getBillDetailId());
				// 校验截止时间
				if (new Date().after(detail.getBillEndTime())) {
					throw new AppCheckException("school.zhangdan.billEndTime.code", "school.zhangdan.billEndTime.message");
				}
				SmsMessageReq param = new SmsMessageReq();
				param.setMsgKey("sms.school.prompt.payment");
				param.setTemplateType(0);
				param.setMobile(mobileAndBill.getMobile());
				List<String> lis = Arrays.asList(detail.getStudentName(), selectById.getSchoolName());
				param.setParams(lis.toArray());
				Map<String, Object> map = smsApi.sendMessage(param);
				String code = JSON.toJSONString(map.get("code"));
				Integer result1 = Integer.parseInt(code);
				if (result1 == 200) {
					SmsSend entity = new SmsSend();
					entity.setSchoolId(oneUser.getSchoolId());
					entity.setClassId(detail.getClassId());
					entity.setClassName(detail.getClassName());
					entity.setMobile(mobileAndBill.getMobile());
					entity.setCreatorId(Long.parseLong(currentUser.getId() + ""));
					entity.setCreateTime(new Date());
					entity.setCreatorRole(oneUser.getRoleid());
					entity.setCreatorName(oneUser.getName());
					entity.setSendName(detail.getStudentName());
					entity.setStatus(SystemConstans.YES);
					smsList.add(entity);
					successSms.add(1);
				} else {
					SmsSend entity = new SmsSend();
					entity.setSchoolId(oneUser.getSchoolId());
					entity.setFalseMessage(JSON.toJSONString(map.get("message")).replaceAll("\"", ""));
					entity.setClassId(detail.getClassId());
					entity.setClassName(detail.getClassName());
					entity.setMobile(mobileAndBill.getMobile());
					entity.setCreatorId(Long.parseLong(currentUser.getId() + ""));
					entity.setCreateTime(new Date());
					entity.setCreatorRole(oneUser.getRoleid());
					entity.setCreatorName(oneUser.getName());
					entity.setSendName(detail.getStudentName());
					entity.setStatus(SystemConstans.NO);
					smsList.add(entity);
				}
			}
			// 短信发送情况
			smsSendMapper.insertBatch(smsList);
			// 发送成功的数目
			int successSize = successSms.size();
			return successSize;
		}
		return 0;
	}

	private void reduceSchoolBuySms(User oneUser, SchoolInfo selectById, long consumerCount) {

		// 扣除学校购买短信余额
		SmsSchoolBuyRecord smsSchoolBuy = new SmsSchoolBuyRecord();
		smsSchoolBuy.setSchoolId(oneUser.getSchoolId());
		smsSchoolBuy.setSmsBuyCount(consumerCount);
		smsSchoolBuy.setSchoolName(selectById.getSchoolName());
		smsSchoolBuy.setUpdaterId(Long.parseLong(oneUser.getId() + ""));
		smsSchoolBuy.setUpdateTime(new Date());
		Map<String, Object> smsSchoolBuyReduce = smsApi.smsSchoolBuyReduce(smsSchoolBuy);
		if (smsSchoolBuyReduce.get("code").equals(200)) {
			String data3 = JSON.toJSONString(smsSchoolBuyReduce.get("data"));
			if (!data3.equals("null")) {
				SuccessTip sr2 = JSON.parseObject(data3, SuccessTip.class);
				Integer result2 = sr2.getCode();
				if (result2 == 400) {
					throw new AppCheckException("sms.school.balance.notEnough.exit.code", "sms.school.balance.notEnough.exit.message");
				}

			}
		}
	}

	/**
	 * 方法描述: [学校短信消费情况列表.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月18日-下午5:49:46<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public Page<SmsSend> smsSchoolSendList(Page<SmsSend> page, SmsSendRecordReq query) {

		extracted(query);

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		Long schoolId = oneUser.getSchoolId();
		if (schoolId == null) {
			throw new AppCheckException("school.noSchool.code", "school.noSchool.message");
		}
		SchoolInfo selectById = schoolInfoMapper.selectById(schoolId);
		if (selectById != null) {
			query.setSchoolId(oneUser.getSchoolId());
			List<SmsSend> list = smsSendMapper.pageList(page, query.getSearch());
			page.setRecords(list);
			return page;
		} else {
			throw new AppCheckException("school.noSchool.code", "school.noSchool.message");
		}

	}

	private void extracted(SmsSendRecordReq query) {

		if (query.getStartTime() != null) {
			query.setStartTime(DateUtil.formate(query.getStartTime(), true));
		}
		if (query.getEndTime() != null) {
			query.setEndTime(DateUtil.formate(query.getEndTime(), false));
		}
	}

	/**
	 * 方法描述: [学校短信使用情况.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月19日-上午10:04:34<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@SuppressWarnings("deprecation")
	@Override
	public SmsBalanceVo getSmsSchoolBalance() {

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		Long schoolId = oneUser.getSchoolId();
		if (schoolId == null) {
			throw new AppCheckException("school.noSchool.code", "school.noSchool.message");
		}
		SchoolInfo selectById = schoolInfoMapper.selectById(oneUser.getSchoolId());
		if (selectById != null) {
			SmsBalanceVo vo = new SmsBalanceVo();

			Long canUse = 0L;
			Calendar cal = Calendar.getInstance();
			int freeMonth = cal.get(Calendar.MONTH) + 1;
			Map<String, Object> map = smsApi.getSmsSchoolgive(schoolId, freeMonth + ",");
			if (map.get("code").equals(200)) {
				String data = JSON.toJSONString(map.get("data"));
				SmsSchoolGiveReq sr = JSON.parseObject(data, SmsSchoolGiveReq.class);
				if (sr != null) {
					vo.setCurrentMonthfreeCount(sr.getGiveCount().toString());
					canUse += sr.getGiveCount();
				}
			}

			vo.setCurrentMonthfreeCount("0");

			Map<String, Object> smsSchoolBuyMap = smsApi.getSmsSchoolBuy(schoolId);

			if (smsSchoolBuyMap.get("code").equals(200)) {
				String data = JSON.toJSONString(smsSchoolBuyMap.get("data"));

				if (!data.equals("null") && StringUtils.isNotBlank(data)) {
					canUse += Integer.parseInt(data);
				}
			}
			vo.setSchoolCanUseBalance(canUse.toString());
			return vo;

		} else {
			throw new AppCheckException("school.noSchool.code", "school.noSchool.message");
		}

	}

	/**
	 * 方法描述: [上下架.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月19日-下午12:31:36<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public Map statusChange(SmsPackageReq param) {

		ShiroUser currentUser = ShiroKit.getUser();
		Integer status = param.getStatus();
		if (param.getId() == null) {
			param.setCreateTime(new Date());
			param.setCreatorId(Long.parseLong(currentUser.getId() + ""));
		} else {
			Map<String, Object> map = smsApi.getSmsPackageById(param.getId());
			if (map.get("code").equals(200)) {
				String data = JSON.toJSONString(map.get("data"));
				SmsPackage s = JSON.parseObject(data, SmsPackage.class);
				if (s == null || s.getIsDelete() == SystemConstans.YES) {

					throw new AppCheckException("school.sms.package.null.code", "school.sms.package.null.message");
				}
				if (s.getVersionNo() != param.getVersionNo()) {
					throw new AppCheckException("versionNo.outofDate.code", "versionNo.outofDate.message");
				}
				BeanUtils.copyProperties(s, param);
			}
			param.setStatus(status);
			param.setUpdateTime(new Date());
			param.setUpdaterId(Long.parseLong(currentUser.getId() + ""));
		}
		return smsApi.addSmsPackage(param);
	}

	/**
	 * 方法描述: [短信账单支付成功.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月20日-下午6:19:19<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public void successCheckSchoolSmsRecord(String orderNo) {

		Map<String, Object> map = smsApi.getSchoolRecord(orderNo);
		if (map.get("code").equals(200)) {
			String data = JSON.toJSONString(map.get("data"));
			SmsSchoolRecord sr = JSON.parseObject(data, SmsSchoolRecord.class);
			if (sr == null) {
				throw new AppCheckException("order.pay.code", "order.pay.message", "订单编号错误");
			}
			if (sr.getStatus() == SystemConstans.NO) {
				throw new AppCheckException("order.pay.code", "order.pay.message", "未支付！");
			}
		}
	}

	/**
	 * 方法描述: [获取学校充值短信订单.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月21日-上午11:24:55<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public SmsSchoolRecord getSchoolRecord(String orderNo) {

		ShiroUser currentUser = ShiroKit.getUser();
		User oneUser = userMapper.selectById(currentUser.getId());
		if (!oneUser.getStatus().equals(SystemConstans.YES)) {
			throw new AppCheckException("school.user.notActive.code", "school.user.notActive.message");
		}
		Long schoolId = oneUser.getSchoolId();
		if (schoolId == null) {
			throw new AppCheckException("school.user.noSchool.code", "school.user.noSchool.message");
		}
		Map<String, Object> map = smsApi.getSchoolRecord(orderNo);
		if (map.get("code").equals(200)) {
			String data = JSON.toJSONString(map.get("data"));
			SmsSchoolRecord sr = JSON.parseObject(data, SmsSchoolRecord.class);
			if (sr == null) {
				throw new AppCheckException("order.pay.code", "order.pay.message", "订单编号错误");
			}
			SortedMap<String, String> commentSign = new TreeMap<String, String>();
			commentSign.put("orderNo", orderNo + "");
			commentSign.put("key", sr.getId() + "");
			commentSign.put("userMobile", oneUser.getPhone());
			String csign = PayUtil.createSign(commentSign);
			sr.setSign(csign);
			return sr;
		} else {
			throw new AppCheckException("sms.school.smsRecord.false.code", "sms.school.smsRecord.false.message");
		}
	}

	/**
	 * 方法描述: [定时任务学校赠送短信.每月的1号凌晨1点执行]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月23日-下午2:28:28<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	// @Scheduled(cron = "0 0 0 1 * ?")
	@Transactional
	public void giveSchoolsms() {

		List<SchoolInfo> smsSchoolgive = schoolInfoMapper.selectList(new EntityWrapper<SchoolInfo>()
				.eq("is_delete", SystemConstans.NO).gt("give_count", SystemConstans.NO));
		if (CollectionUtils.isNotEmpty(smsSchoolgive)) {
			List<SmsSchoolGiveReq> list = new ArrayList<SmsSchoolGiveReq>();
			for (SchoolInfo req : smsSchoolgive) {
				String freeMonth = req.getFreeMonth();
				logger.info("免费月份:{}", freeMonth);
				int month = DateUtil.getDate().getMonth() + 1;
				// 当月存在免费赠送
				if (freeMonth.indexOf(month + ",") != -1) {
					SmsSchoolGiveReq give = new SmsSchoolGiveReq();
					give.setSchoolId(req.getId());
					give.setIsDelete(SystemConstans.NO);
					give.setCreateTime(new Date());
					give.setFreeMonth(month + ",");
					give.setGiveCount(req.getGiveCount());
					list.add(give);
					// 免费短信,没用完就还回去
					Map<String, Object> schoolSmsFree = smsApi.getSmsSchoolgive(req.getId(), month + ",");
					if (schoolSmsFree.get("code").equals(200)) {
						String free = JSON.toJSONString(schoolSmsFree.get("data"));
						if (!free.equals("null")) {
							SmsSchoolGiveReq smsfree = JSON.parseObject(free, SmsSchoolGiveReq.class);
							Long smsFreeCount = smsfree.getGiveCount();
							if (smsFreeCount > 0) {
								// 后台购买数量减去相应是的数目 param.getGiveSmsCount()
								Map<String, Object> mapSms = smsApi.getTopSmsBuyBalance();
								if (mapSms.get("code").equals(200)) {
									String buy = JSON.toJSONString(mapSms.get("data"));
									if (!buy.equals("null")) {
										SmsBuyRecord smsBuyRecord = JSON.parseObject(buy, SmsBuyRecord.class);
										smsBuyRecord.setSmsBuyCount(smsFreeCount);
										smsBuyRecord.setUpdateTime(new Date());
										smsBuyRecord.setCreatorName(req.getSchoolContactPeople());
										smsApi.smsBuyAdd(smsBuyRecord);
									}
								}

							}
						}
					}
				}
			}
			smsApi.addSmsSchoolGiveList(list);

		}
	}

	/**
	 * 方法描述: [定时任务学校赠送短信.每月的1号凌晨9点执行]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年7月23日-下午2:28:28<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	// @Scheduled(cron = "0 0 9 1 * ?")
	@Transactional
	public void sendSchoolsms() {

		List<SchoolInfo> smsSchoolgive = schoolInfoMapper.selectList(new EntityWrapper<SchoolInfo>()
				.eq("is_delete", SystemConstans.NO).gt("give_count", SystemConstans.NO));
		if (CollectionUtils.isNotEmpty(smsSchoolgive)) {
			for (SchoolInfo req : smsSchoolgive) {
				String freeMonth = req.getFreeMonth();
				logger.info("免费月份:{}", freeMonth);
				int month = DateUtil.getDate().getMonth() + 1;
				// 当月存在免费赠送
				if (freeMonth.indexOf(month + ",") != -1) {
					// 发送短信给学校联系人，短信赠送已修改
					SmsMessageReq sms = new SmsMessageReq();
					sms.setMsgKey("sms.school.give.update");
					sms.setTemplateType(0);
					sms.setMobile(req.getContactTel());
					List<String> lis = Arrays.asList(req.getSchoolContactPeople());
					sms.setParams(lis.toArray());
					smsApi.sendMessage(sms);
				}
			}

		}
	}

	/**
	 * 方法描述: [学校每月消费短信情况.]<br/>
	 * 初始作者: 钟小平<br/>
	 * 创建日期: 2018年8月29日-上午11:37:31<br/>
	 * 开始版本: 2.0.0<br/>
	 * =================================================<br/>
	 * 修改记录：<br/>
	 * 修改作者 日期 修改内容<br/>
	 * ================================================<br/>
	 */
	@Override
	public Page<SmsSchoolUseVo> smsSchoolUseList(Page<SmsSchoolUseVo> page, SchoolSmsUseReq schoolSmsUseReq) {

		String time = schoolSmsUseReq.getTime();
		if (StringUtils.isNotBlank(time)) {
			Date startTime = DateUtil.parse(time + "-01 00:00:00", "yyyy-MM-dd HH:mm:ss");
			Date endTime = DateUtil.addMonthsToDate(startTime, 1);
			schoolSmsUseReq.setStartTime(startTime);
			schoolSmsUseReq.setEndTime(endTime);
		}
		List<SmsSchoolUseVo> list = smsSendMapper.smsSchoolUseList(page, schoolSmsUseReq.getSearch());
		page.setRecords(list);
		return page;
	}
}
